package com.all.play.myrxjava;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.Toast;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 聪明一只哈 on 2018/5/18.
 * Time: 2018/5/18  11:59
 */

public class FristActivity extends AppCompatActivity {

    private ImageView image;
    private Subscriber<Drawable> subscriber;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);

        final int drawableRes=R.mipmap.ic_launcher;
        image = (ImageView) findViewById(R.id.image);

        subscriber = new Subscriber<Drawable>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(FristActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(Drawable drawable) {
                image.setImageDrawable(drawable);
            }
        };


        Observable<Drawable> observable = Observable.create(new Observable.OnSubscribe<Drawable>() {
            @Override
            public void call(Subscriber<? super Drawable> subscriber) {
                Drawable drawable = getTheme().getDrawable(drawableRes);
                subscriber.onNext(drawable);
                subscriber.onCompleted();

            }
        });

        observable
                .subscribeOn(Schedulers.io())//指定被观察者运行的线程,在 IO 线程,相当于子线程
                .observeOn(AndroidSchedulers.mainThread())//指定观察者运行的线程, Subscriber 的回调发生在主线程
                .subscribe(subscriber);


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(subscriber.isUnsubscribed()){
            subscriber.unsubscribe();
        }

    }
}
